package com.xiyi.shouxin.utils;



import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;


import com.aliyun.teaopenapi.models.Config;



/**
 * 阿里云短信
 */
public class SendMsgUtils {

    // 这些参数建议放到配置文件里，这里写死仅为演示
    private static final String ACCESS_KEY_ID = "LTAI5t9LEu5VuBVSVzKSSiAC";
    private static final String ACCESS_KEY_SECRET = "2ZgXlIHbfQWxnnuQtdIKGvqMkfeg5L";
    private static final String SIGN_NAME = "心所欲电子科技上海";
    private static final String TEMPLATE_CODE = "SMS_314786394";

    private static Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(ACCESS_KEY_ID)
                .setAccessKeySecret(ACCESS_KEY_SECRET);
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 发送短信验证码
     * @param phone 手机号
     * @param code 验证码
     * @return 是否发送成功
     */
    public static boolean sendSms(String phone, String code) {
        try {
            Client client = createClient();
            SendSmsRequest request = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName(SIGN_NAME)
                    .setTemplateCode(TEMPLATE_CODE)
                    .setTemplateParam("{\"code\":\"" + code + "\"}");
            SendSmsResponse response = client.sendSms(request);
            return "OK".equals(response.getBody().getCode());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
